# 第一步，安装模块 pip  install flask

from flask import Flask, render_template, request
from esrk import *
import requests
from lxml import etree
# 创建一个Flask实例
#template_folder的含义是html页面在哪个文件夹下，默认值是templates
# static_fold的含义是css、js、image等在哪个文件夹下，默认值是static
app = Flask(__name__, template_folder='', static_folder='', static_url_path='')

@app.route('/')     #单引号里面是访问路径
def index():
    # 爬虫
    create_index('rank_index')
    for i in range(10):
        url = 'https://movie.douban.com/top250?start={}'.format(i * 25)
        # print(url) 每页25条
        header = {
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36"}
        data = requests.get(url, headers=header, timeout=100).text
        s = etree.HTML(data)
        # 先爬取标签的共同部分    此时不加解析 它就是一个元素 <Element li at 0x31cdb48>
        file = s.xpath('//*[@id="content"]/div/div[1]/ol/li')

        for move_total in file:
            move_link = move_total.xpath('.//a/@href')[0]
            move_name = move_total.xpath('./div/div[2]/div[1]/a/span[1]/text()')[0]
            move_score = move_total.xpath('./div/div[2]/div[2]/div/span[2]/text()')[0]
            move_actor = move_total.xpath('./div/div[2]/div[2]/p[1]/text()')[0]
            move_detailed = move_total.xpath('./div/div[2]/div[2]/p[1]/text()')[1]
            move_img = move_total.xpath('./div/div[1]/a/img/@src')[0]
            move_pingjia = move_total.xpath('./div/div[2]/div[2]/div/span[4]/text()')[0]
            # print(move_img)
            #         -------------------------调用insert_index完成插入数据-------------
            insert_index('rank_index', move_link, {
                'title': move_name,
                'link': move_link,
                'score': move_score,
                'actor': move_actor,
                'detailed': move_detailed,
                'img': move_img,
                'pingjia': move_pingjia
            })
    search1('rank_index', '电影')
    return render_template('index.html')          # index.html默认的位置是在app.py同级的文件夹templates中的，返回给客户端

@app.route('/search')
def search():
    kw = request.args.get("kw")
    print('关键词', kw)
    ## 在这里，调用python代码，访问es，获取查询结果
    ## 下面result中对象的字段，一定与html页面的字段对应
    # result = [{"title":"啊啊啊啊","content":"八八八八asddaddasd"}]
    result = search1('rank_index', kw)
    return render_template('index.html', kw=kw, result=result)

if __name__ == '__main__':
    app.run(debug=True, port=5000) # 启动一个flask服务器，默认端口是5000
